package com.soc.auth.controller;

import cn.hutool.core.util.RandomUtil;
import com.soc.auth.constants.RedisConstants;
import com.soc.auth.service.impl.AliyunSmsService;
import com.soc.auth.utils.ResultResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
@Slf4j
@Validated
// 单参数校验时需要在类上加上@Validated，否则不生效
public class SmsController {

    private final AliyunSmsService aliyunSmsService;

    private final RedisTemplate<String, Object> redisTemplate;


    // 发送短信验证码
    @GetMapping("/sendSmsCode")
    public ResultResponse<Object> sendSmsCode(@NotBlank(message = "手机号不能为空！") String phone) {

        String captcha = RandomUtil.randomNumbers(6); // 随机生成6位的验证码
//        log.info("手机号：{}的验证码为：{}", phone, captcha);
//        // 将验证码存到Redis中
//        redisTemplate.opsForValue().set(RedisConstants.CAPTCHA_KEY + phone, captcha,
//                RedisConstants.CAPTCHA_TTL, TimeUnit.SECONDS);
//        return ResultResponse.success(captcha);

        boolean b = aliyunSmsService.sendSmsCode(phone, captcha);
        if (b) {
            // 将短信验证码保存到Redis中
            redisTemplate.opsForValue().set(RedisConstants.CAPTCHA_KEY + phone, captcha,
                    RedisConstants.CAPTCHA_TTL, TimeUnit.SECONDS);
        }
        return ResultResponse.judge(b);

    }
}
